package com.yf.ccdugtfood.robot;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.yf.ccdugtfood.R;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class RobotActivity extends AppCompatActivity {
    private ListView listView;
    private ChatAdapter adapter;
    private List<ChatBean> chatBeanList;  //存放所有聊天数据集合
    private EditText et_send_msg;
    private Button btn_send;
    //接口地址
    private static final String WEB_SITE = "http://www.tuling123.com/openapi/api";
    private static final String KEY = "cde682f8ac5d464e9da114d1b87b66fd";
    private String sendMsg;        //发送的信息
    private String welcome[];      //存储欢迎信息
    private MHandler mHandler;
    public static final int MSG_OK = 1;    //获取数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_robot);
        chatBeanList = new ArrayList<ChatBean>();
        mHandler = new MHandler();
        welcome = getResources().getStringArray(R.array.welcome);
        initView();
    }

    private void initView() {
        listView = findViewById(R.id.list);
        et_send_msg = findViewById(R.id.et_send_msg);
        btn_send = findViewById(R.id.btn_send);
        adapter = new ChatAdapter(chatBeanList,this);
        listView.setAdapter(adapter);
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendData();
            }
        });
        et_send_msg.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN){
                    sendData();
                }
                return false;
            }
        });
    }

    private void sendData() {
        sendMsg = et_send_msg.getText().toString().trim(); //获取你输入的信息
        if (TextUtils.isEmpty(sendMsg)){
            Toast.makeText(this,"您还没输入任何信息哦！",Toast.LENGTH_SHORT).show();
            return;
        }
        et_send_msg.setText("");
        sendMsg = sendMsg.replaceAll(" ","").replaceAll("\n","").trim();
        ChatBean chatBean = new ChatBean();
        chatBean.setMessage(sendMsg);
        chatBean.setState(chatBean.SEND);      //表示自己发送的信息
        chatBeanList.add(chatBean);
        adapter.notifyDataSetChanged();      //更新ListView列表
        getDataFromServer();
    }

    private void getDataFromServer() {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(WEB_SITE + "?key=" + KEY + "&info="+ sendMsg).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Message msg = new Message();
                msg.what = MSG_OK;
                msg.obj = res;
                mHandler.sendMessage(msg);
            }
        });
    }

    /**
     * 事件捕获
     */
    class MHandler extends Handler {
        @Override
        public void dispatchMessage(@NonNull Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case MSG_OK:
                    if (msg.obj != null) {
                        String vlResult = (String) msg.obj;
                        paresData(vlResult);
                    }
                    break;
            }
        }
    }

    private void paresData(String JsonData) {   //Json解析
        try {
            JSONObject jsonObject = new JSONObject(JsonData);
            String content = jsonObject.getString("text");  //获取的机器人信息
            int code = jsonObject.getInt("code");           //服务器状态码
            updateView(code, content);
        } catch (JSONException e) {
            e.printStackTrace();
            showData("客官，您的网络状态不太好哦");
        }
    }

    private void updateView(int code, String content) {
        switch (code) {
            case 4004:
                showData("客官，到点下班啦，拜拜，明天再来找我吧");
                break;
            case 40005:
                showData("客官，你说的是外星语吗？");
                break;
            case 40006:
                showData("客官，今天系统维护哦，暂不接单啦");
                break;
            case 40007:
                showData("客官，待会再和你联系，我这边网络通信状态不太好。。。");
            default:
                showData(content);
                break;

        }
    }

    private void showData(String message) {
        ChatBean chatBean = new ChatBean();
        chatBean.setMessage(message);
        chatBean.setState(ChatBean.RECEIVE);  //表示接收到机器人发送的信息
        chatBeanList.add(chatBean);
        adapter.notifyDataSetChanged();
    }
}
